package com.rightsidetech.http.controller.userApp.coupon;

import com.gexin.fastjson.JSONArray;
import com.rightsidetech.activity.dto.request.*;
import com.rightsidetech.activity.dto.response.ActCouponAllResp;
import com.rightsidetech.activity.dto.response.ActCouponCountInfoResp;
import com.rightsidetech.activity.dto.response.ActCouponStoreGetResp;
import com.rightsidetech.activity.dto.response.ActFindCouponResp;
import com.rightsidetech.activity.service.ActCouponUserService;
import com.rightsidetech.commom.base.ResponseData;
import com.rightsidetech.commom.enums.CodeIdEnum;
import com.rightsidetech.commom.utils.BeanValidator;
import com.rightsidetech.http.aspect.Log;
import com.rightsidetech.http.aspect.Token;
import com.rightsidetech.http.base.BaseController;
import com.rightsidetech.system.entity.store.SysStoreInfo;
import com.rightsidetech.system.service.SysStoreInfoService;
import com.rightsidetech.trade.service.TdCouponUseService;
import com.rightsidetech.user.dtos.response.UsLoginNameResp;
import com.rightsidetech.user.service.UserInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shenyu.client.springmvc.annotation.ShenyuSpringMvcClient;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import java.math.BigDecimal;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @Author: yhr
 * @Date: 2022-01-10 13:53
 */
@RestController
@RequestMapping("/userApp/coupon")
@ShenyuSpringMvcClient(path = "/storeApp/coupon/**")
@Api(tags = "用户优惠券相关")
public class AppCouponController extends BaseController {

    @Resource
    private ActCouponUserService actCouponUserService;
    @Resource
    private UserInfoService userInfoService;
    @Resource
    private TdCouponUseService tdCouponUseService;
    @Resource
    private SysStoreInfoService sysStoreInfoService;

    @Log
    @Token
    @GetMapping("/couponActivity")
    @ApiOperation("查看当前优惠活动")
    public ResponseData<List<ActFindCouponResp>> findCoupon(){
        Long loginInfoId = Long.parseLong(getAttributeForLoginId());
        UsLoginNameResp nameResp = userInfoService.selectByPrimaryKey(loginInfoId);
        if (ObjectUtils.isEmpty(nameResp)){
            return ResponseData.fail(CodeIdEnum.NOLOGINACCOUNT);
        }
        return actCouponUserService.findCoupon(nameResp.getLevel(),Long.parseLong(getAttribute()));
    }

    @Log
    @Token
    @GetMapping("/cardBag")
    @ApiOperation("卡包 (全部不传 1快到期)")
    public ResponseData<List<ActCouponCountInfoResp>> cardBag(CardBagReq req){
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        Byte cardBagFlag = StringUtils.isEmpty(req.getType())?null:Byte.valueOf(req.getType());

        Long userInfoId = Long.parseLong(getAttribute());
        return actCouponUserService.cardBag(userInfoId,cardBagFlag);
    }

    @Log
    @Token
    @GetMapping("/codInfo")
    @ApiOperation("查看优惠券")
    public ResponseData<ActCouponCountInfoResp> codInfo(ActCouponCodeReq req){
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }

        Long loginInfoId = Long.parseLong(getAttributeForLoginId());
        UsLoginNameResp nameResp = userInfoService.selectByPrimaryKey(loginInfoId);
        if (ObjectUtils.isEmpty(nameResp)){
            return ResponseData.fail(CodeIdEnum.NOLOGINACCOUNT);
        }
        return actCouponUserService.codeInfo(req.getCode(),Long.parseLong(getAttribute()),nameResp.getLevel());
    }

    @Log
    @Token
    @PostMapping("/getCoupon")
    @ApiOperation("领取用户优惠券")
    public ResponseData getCoupon(@RequestBody ActGetCouponReq req){
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        Long loginInfoId = Long.parseLong(getAttributeForLoginId());
        UsLoginNameResp nameResp = userInfoService.selectByPrimaryKey(loginInfoId);
        if (ObjectUtils.isEmpty(nameResp)){
            return ResponseData.fail(CodeIdEnum.NOLOGINACCOUNT);
        }
        req.setUserInfoId(Long.parseLong(getAttribute()));
        req.setPhoneNo(nameResp.getLoginName());
        req.setPetName(nameResp.getPetName());
        return actCouponUserService.getCoupon(req,nameResp.getLevel());
    }

    @Log
    @Token
    @GetMapping("/couponCountInfo")
    @ApiOperation("用户优惠券列表")
    public ResponseData<List<ActCouponAllResp>> couponCountInfo(ActCouponCountInfoReq actCouponCountInfoReq){
        Long loginInfoId = Long.parseLong(getAttribute());
        if (StringUtils.isEmpty(actCouponCountInfoReq.getAmount())){
            return ResponseData.fail("金额不能为空");
        }
        Long agentInfoId = sysStoreInfoService.selectAgentIdByStoreId(actCouponCountInfoReq.getStoreInfoId());
        List<ActCouponAllResp> responseData = actCouponUserService.couponCountInfo(loginInfoId,actCouponCountInfoReq);
        for (ActCouponAllResp allResp:responseData){
            List<Long> list = JSONArray.parseArray(allResp.getUseScope(),Long.class);
            boolean flag = list.contains(agentInfoId);
            if(!flag) {
                allResp.setUsed((byte) 1);
            }
            //只添加可以使用的优惠券
            //折扣优惠券
            if("0".equals(allResp.getCouponType())&&allResp.getUsed()==(byte)0){
                allResp.setRealAmount(actCouponCountInfoReq.getAmount().multiply(allResp.getAmount()).divide(new BigDecimal(10),2,BigDecimal.ROUND_DOWN));
                //如果实际优惠金额大于最多抵扣额度
                if(allResp.getRealAmount().compareTo(allResp.getMaxDiscountAmount())>=0){
                    allResp.setRealAmount(allResp.getMaxDiscountAmount());
                }
            }
            //满减优惠券
            if ("1".equals(allResp.getCouponType())&&allResp.getUsed()==(byte)0){
                allResp.setRealAmount(allResp.getAmount());
            }
        }
//
//        responseData.stream()
//                .sorted(
//                        Comparator.comparing(ActCouponAllResp::getUsed)
//                                .thenComparing(Comparator.comparing(ActCouponAllResp::getRealAmount).reversed())
//                ).collect(Collectors.toList());


        responseData.sort(new Comparator<ActCouponAllResp>() {
            @Override
            public int compare(ActCouponAllResp o1, ActCouponAllResp o2) {
                int a = 0;
                a = o1.getUsed()-o2.getUsed();
                if (a ==0 ){
                    a = o2.getRealAmount().compareTo(o1.getRealAmount());
                }
                return a;
            }
        });

        return ResponseData.success(responseData);
    }

    @Log
    @Token
    @GetMapping("/getStoreCoupon")
    @ApiOperation("扫码获取门店优惠券")
    public ResponseData<ActCouponStoreGetResp> getStoreCoupon(ActGetStoreCouponReq req){
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        Long userInfoId = Long.parseLong(getAttribute());
        SysStoreInfo sysStoreInfo = sysStoreInfoService.selectByPrimaryKeyByStatus(req.getStoreId());
        if(StringUtils.isEmpty(sysStoreInfo)){
            return ResponseData.fail(CodeIdEnum.NonStoreInfo);
        }
        Long agentInfoId = sysStoreInfo.getSysAgentInfoId();
        return actCouponUserService.getCodeByActivityNoAndAgentInfoId(req,agentInfoId, userInfoId);
    }



}
